import { computed, onBeforeUnmount, onMounted, ref, unref } from "vue";
const useDragable = (target, limitDOM) => {
  let _top = ref(0);
  let _left = ref(0);
  let _disTop = ref(0);
  let _disLeft = ref(0);

  const dropEvent = (e) => {
    // 设置边界
    let _t = e.y - _disTop.value;
    let _l = e.x - _disLeft.value;
    let _t_max =
      limitDOM.value.offsetHeight -
      target.value.offsetHeight +
      limitDOM.value.offsetTop;
    let _l_max =
      limitDOM.value.offsetWidth -
      target.value.offsetWidth +
      limitDOM.value.offsetLeft;
    if (_t <= limitDOM.value.offsetTop) {
      _t = limitDOM.value.offsetTop;
    }
    if (_l <= limitDOM.value.offsetLeft) {
      _l = limitDOM.value.offsetLeft;
    }
    if (_l >= _l_max.value) {
      _l = _l_max.value;
    }
    if (_t >= _t_max.value) {
      _t = _t_max.value;
    }
    _top.value = _t;
    _left.value = _l;
  };
  const dragStart = (e) => {
    _disTop.value = e.y - _top.value;
    _disLeft.value = e.x - _left.value;
  };
  const dragMove = (e) => {
    e.preventDefault();
  };
  onMounted(() => {
    if (!unref(target)) {
      return;
    }
    _left.value = limitDOM.value.offsetLeft;
    _top.value = limitDOM.value.offsetTop;
    target.value.addEventListener("dragstart", dragStart);
    limitDOM.value.addEventListener("dragover", dragMove);
    limitDOM.value.addEventListener("drop", dropEvent);
  });
  onBeforeUnmount(() => {
    if (unref(target)) {
      target.value.removeEventListener("dragstart", dragStart);
      limitDOM.value.removeEventListener("dragover", dragMove);
      limitDOM.value.removeEventListener("drop", dropEvent);
    }
  });
  return {
    left: computed(() => _left.value),
    top: computed(() => _top.value),
  };
};

export default useDragable;
